Skip to main content

Object in ES6

Equality

tip
  • equality in JavaScript ES5 using '==' and '==='; and introduction to the Object.is() method in ES6, which is very similar to '==='
  • == will compare the values.
  • === will compare the values and the types. :::
the difference between === and Object.is(x,y)
console.log(Object.is(+0, -0)) // is `false`, while
console.log(-0 === +0) // is `true`

Object.is(NaN, NaN) // is `true`, while
console.log(NaN === NaN) // is false

Mixins with Object.assign(a,b)

let horse = {
horseName: "QuickBucks",
toString: function () {
return this.horseName
}
}

let rider = {
riderName: "Frank",
toString: function () {
return this.riderName
}
}

let horseRiderStringUtility = {
toString: function () {
return this.riderName + " on " + this.horseName
}
}

// mixins all of the object above.
let racer = Object.assign(
{}, // It's better to add an empty object, otherwise the horse will be mutated(changed).
horse,
rider,
horseRiderStringUtility
)

console.log(racer.toString()) // The output is : Frank on QuickBucks

Object Prototype Extensions and Super Calls

  • first the prototype of obj is {}
  • when we invoke setPrototypeOf(obj, proto), the prototype of obj becomes proto
  • so finally we change the parent object of the obj. :::
let proto = {
whoami() {
console.log("I am proto")
}
}

let obj = {
whoami() {
super.whoami()
console.log("I am obj")
}
}

console.log(Object.getPrototypeOf(obj))
//{}

Object.setPrototypeOf(obj, proto)

obj.whoami()
// I am proto
// I am obj

defineProperty

const obj = {
x: 1,
y: 2
}

console.log(obj)

/**
configurable: 是否可删除
enumerable: 是否可迭代
writable: 是否可修改
value: 数值

{
x: { value: 1, writable: true, enumerable: true, configurable: true },
y: { value: 2, writable: true, enumerable: true, configurable: true }
}

*/
console.log(Object.getOwnPropertyDescriptors(obj))

Object.defineProperty(obj, "x", {
configurable: false, // 不能删
writable: false, // 不能改
enumerable: false // 不能迭代
})

// delete obj.x
obj.x = 10

console.log(obj)

// get set方法劫持
Object.defineProperty(obj, "y", {
get() {
console.log("get value")
return 0
},
set() {
console.log("set value")
}
})

console.log(obj.y)
obj.y = 100